/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe*/
probe.filter("toSourceCode", function () {
	var stringWrapper = function (obj) {
		if (typeof obj === "string") {
			return '"' + obj.toString() + '"';
		}

		return obj.toString();
	};

	var buildInsFromType = [
		//0.wait
		function (stmt) {
			return 'wait ' + stmt.BODY.delay + ";\n";
		},
		//1.action
		function (stmt) {
			var out = stmt.BODY.action + " " + stringWrapper(stmt.BODY.object);

			if (stmt.BODY.param !== null && stmt.BODY.param !== undefined) {
				if (stmt.BODY.paramType === 1) {
					out += " by [" + stringWrapper(stmt.BODY.param) + "]";
				} else {
					out += " by " + stringWrapper(stmt.BODY.param);
				}
			}
			out += ";\n";

			return out;
		},
		//2.assert
		function (stmt) {
			var out = "assert " + stringWrapper(stmt.BODY.exp);

			if (stmt.BODY.timeout !== undefined) {
				out += " in " + stmt.BODY.timeout;
			}
			if (stmt.BODY.key !== undefined) {
				out += " as " + stringWrapper(stmt.BODY.key);
			}
			out += ";\n";

			return out;
		}
	];

	return function (input, isSave) {
		var out = '', macro = '#set ', ins = angular.copy(input.instructions);

		if (isSave) {
			out += '//simple case\n';
		}

		if (!input.noOrigin) {
			out += macro + 'ORIGIN ' + input.origin + ';\n';
		}
		out += macro + 'MAX_LOOP ' + input.maxLoop + ';\n';
		out += macro + 'NEXT_LOOP_DELAY ' + input.nextLoopDelay + ';\n\n';
		out += 'process main {\n';
		
		angular.forEach(ins, function (item, index) {
			out += '\t';
			if (!isSave) {
				out += "_" + index + ":";
			}

			out += buildInsFromType[item.TYPE](item);
		});
		
		out += '}';

		return out;
	};
}).filter('toSourceCodeForSimpleView', function () {
	return function () {
		return '过滤了';
	};
});
